package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Result;
import com.itheima.service.CategoryService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public Result add(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateTime(LocalDateTime.now());
        Integer userId = getUserId();
        category.setCreateUser(userId);
        this.save(category);
        return Result.success();
    }

    private Integer getUserId() {
        Map<String, Object> map = ThreadLocalUtil.get();
        return  (Integer) map.get("id");
    }

    @Override
    public Result<List<Category>> getList() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        Integer userId = getUserId();
        queryWrapper.eq(Category::getCreateUser, userId);
        List<Category> list = this.list(queryWrapper);
        return Result.success(list);
    }

    @Override
    public Result<Category> findById(Integer id) {
        Category category = this.getById(id);
        return Result.success(category);
    }
}
